<template>
  <div class="page-wrapper">
    <c-card title="我的任务" class="user-list">
      <el-table ref="table" v-loading="loading" :data="tasks" style="width: 100%" :height="498">
        <el-table-column prop="nodeName" label="节点名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="name" label="工单名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="processName" label="流程名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="priorityId" label="优先级"></el-table-column>
        <el-table-column prop="begin" label="开始时间" width="200"></el-table-column>
        <el-table-column prop="days" label="期限（天）"></el-table-column>
        <el-table-column prop="chargePersonName" label="负责人" show-overflow-tooltip></el-table-column>
        <el-table-column prop="clientName" label="客户" show-overflow-tooltip></el-table-column>
        <el-table-column prop="substationname" label="变电箱/站" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row, $index}">
            <el-button size="small" type="text" @click="showDlg(row, $index)">完成</el-button>
            <el-button size="small" type="text" @click="showDetail(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right;" class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="page.size"
          :current-page.sync="page.index"
          :total="page.total"
          @current-change="_getTasks"
        ></el-pagination>
      </div>
    </c-card>
    <c-dlg title="完成任务" :visible.sync="dialogVisible">
      <el-form
        ref="form"
        :model="finishTask"
        :rules="rules"
        label-width="60px"
        class="demo-ruleForm"
        label-position="top"
      >
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="工作内容" prop="workNote">
              <el-input v-model="finishTask.workNote" size="small" type="textarea"></el-input>
            </el-form-item>
          </div>
        </div>
        <div v-if="curTask && curTask.nodeType !== 2" class="form-row">
          <div class="row-item">
            <el-form-item label="下一步人员" prop="operateUserId">
              <el-select v-model="finishTask.operateUserId" size="small">
                <el-option v-for="u in users" :key="u.pkid" :label="u.username" :value="u.pkid"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="form-row">
          <div class="row-item">
            <el-form-item label="资料附件" prop="workMidea" class="no-margin">
              <el-upload
                :multiple="false"
                :http-request="uploadFile"
                :file-list="fileList"
                class="upload-demo"
                action="1"
                auto-upload
                accept=".pdf, .docx, .doc, .xls, .jpg, jpeg, png, .txt, .zip, .rar"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">请上传图片,文档或压缩文件，且不超过10Mb</div>
              </el-upload>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="finishHandle">提交</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </div>
    </c-dlg>
    <c-dlg :visible.sync="detailVisible" title="详情" :type="2">
      <work-detail :id="curId"></work-detail>
    </c-dlg>
  </div>
</template>

<script>
import CCard from "@/components/CCard";
import CDlg from "@/components/CDlg";
import WorkDetail from "./components/Detail";
import { upload } from "@/api/user";
import { calcPageNum } from "@/utils";
export default {
  name: "Mine",
  components: {
    CCard,
    CDlg,
    WorkDetail
  },
  data() {
    return {
      tasks: null,
      finishTask: {},
      loading: false,
      curTask: null,
      curId: null,
      dialogVisible: false,
      detailVisible: false,
      page: {
        index: 1,
        size: 10,
        total: 0
      },
      users: null,
      // upload
      fileList: [],
      rules: {
        workNote: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ],
        operateUserId: [
          { required: true, message: "该字段不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    "page.index"(v) {
      const path = this.$route.path;
      this.$router.push(path + "?page=" + v);
    }
  },
  mounted() {
    const h = this.$refs["table"].$el.clientHeight;
    const n = calcPageNum(h);
    this.$set(this.page, "size", n);

    const page = this.$route.query.page || 1;
    this.$set(this.page, "index", page);
    this._getTasks();
  },
  methods: {
    _getTasks() {
      const params = {
        page: this.page.index,
        rows: this.page.size
      };
      this.loading = true;
      // todo my task api
      return this.$axios
        .get("plat/work/queryTask", { params })
        .then(res => {
          if (res.code === 1) {
            this.tasks = res.data.rows;
            this.$set(this.page, "total", res.data.total);
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e))
        .finally(() => {
          this.loading = false;
        });
    },
    getNextUser(id) {
      return this.$axios
        .get("plat/work/taskUser?pkid=" + id)
        .then(res => {
          if (res.code === 1) {
            this.users = res.data;
          } else {
            throw res.msg;
          }
        })
        .catch(e => this.$message.error(e));
    },
    showDlg(row) {
      this.curTask = row;
      if (row.nodeType !== 2) {
        this.getNextUser(row.pkid);
      }
      this.dialogVisible = true;
    },
    showDetail(r) {
      this.detailVisible = true;
      this.curId = r.baseId;
    },
    finishHandle() {
      // 提交任务
      const post = {
        pkid: this.curTask.pkid,
        ...this.finishTask
      };
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.fileList[0]) {
            post.url = this.fileList[0].url;
          }
          const load = this.$loading();
          // todo finish task api
          return this.$axios
            .post("plat/work/ediTcurrentTask", post)
            .then(res => {
              if (res.code === 1) {
                this.dialogVisible = false;
                this.$message.success("提交成功!");
                this._getTasks();
                this.fileList = [];
              } else {
                throw res.msg;
              }
            })
            .catch(e => this.$message.error(e))
            .finally(() => load.close());
        }
      });
    },
    uploadFile(f) {
      const size = f.file.size / 1024 / 1024;
      if (size > 10) {
        this.$message.error("文件大于10MB, 无法上传!");
        this.fileList = [];
        return false;
      }
      upload(f)
        .then(u => {
          this.fileList = [
            {
              name: f.file.name,
              url: u
            }
          ];
        })
        .catch(e => {
          this.$message.error(e);
          // this.fileList = [];
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.row {
  justify-content: flex-start;
  .item {
    display: inline-flex;
    align-items: center;
    margin-left: 30px;
    &:nth-child(1) {
      margin-left: 0;
    }
    label {
      margin-right: 8px;
      white-space: nowrap;
      flex-grow: 1;
    }
    .el-input {
      flex-shrink: 1;
    }
  }
}
</style>
